package com.example.seabedmusic.views;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.seabedmusic.R;
import com.example.seabedmusic.adapter.PlaylistAdapter;
import com.example.seabedmusic.entity.Playlist;

import com.example.seabedmusic.utils.PlaylistManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

public class PlaylistActivity extends AppCompatActivity implements PlaylistAdapter.OnPlaylistClickListener {
    private RecyclerView rvPlaylists;
    private PlaylistAdapter adapter;
    private List<Playlist> playlists;
    private PlaylistManager playlistManager;
    private PlaylistUpdateReceiver playlistUpdateReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist);

        initViews();
        loadPlaylists();
        registerPlaylistUpdateReceiver();
    }

    private void registerPlaylistUpdateReceiver() {
        playlistUpdateReceiver = new PlaylistUpdateReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 收到歌单更新广播，刷新数据
                loadPlaylists();
                android.util.Log.d("PlaylistActivity", "收到歌单更新广播，刷新数据");
            }
        };

        // 使用 LocalBroadcastManager 注册接收器
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(playlistUpdateReceiver,
                        new IntentFilter("PLAYLIST_UPDATED"));
    }

    private class PlaylistUpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到歌单更新广播，刷新数据
            loadPlaylists();
            android.util.Log.d("PlaylistActivity", "收到歌单更新广播，刷新数据");
        }
    }

    private void initViews() {
        // 设置标题栏
        TextView tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("我的歌单");

        // 返回按钮
        ImageView ivBack = findViewById(R.id.ivBack);
        ivBack.setOnClickListener(v -> finish());

        // 初始化RecyclerView
        rvPlaylists = findViewById(R.id.rvPlaylists);
        rvPlaylists.setLayoutManager(new LinearLayoutManager(this));

        // 添加歌单按钮
        FloatingActionButton fabAddPlaylist = findViewById(R.id.fabAddPlaylist);
        fabAddPlaylist.setOnClickListener(v -> showCreatePlaylistDialog());
    }

    private void loadPlaylists() {
        playlistManager = PlaylistManager.getInstance();
        playlists = playlistManager.getAllPlaylists();

        if (adapter == null) {
            adapter = new PlaylistAdapter(playlists, this);
            rvPlaylists.setAdapter(adapter);
        } else {
            adapter.updateData(playlists);
        }

        // 打印调试信息
        for (Playlist playlist : playlists) {
            android.util.Log.d("PlaylistActivity",
                    "歌单: " + playlist.getName() +
                            ", 歌曲数量: " + playlist.getSongCount());
        }
    }

    private void showCreatePlaylistDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("新建歌单");

        View dialogView = getLayoutInflater().inflate(R.layout.dialog_create_playlist, null);
        builder.setView(dialogView);

        builder.setPositiveButton("创建", (dialog, which) -> {
            TextView etPlaylistName = dialogView.findViewById(R.id.etPlaylistName);
            TextView etDescription = dialogView.findViewById(R.id.etDescription);

            String name = etPlaylistName.getText().toString().trim();
            String description = etDescription.getText().toString().trim();

            if (!name.isEmpty()) {
                Playlist newPlaylist = playlistManager.createPlaylist(name, description);
                adapter.updateData(playlistManager.getAllPlaylists());
            }
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    @Override
    public void onPlaylistClick(Playlist playlist) {
        // 跳转到歌单详情
        Intent intent = new Intent(this, PlaylistDetailActivity.class);
        intent.putExtra("playlist_id", playlist.getId());
        intent.putExtra("playlist_name", playlist.getName());
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消注册本地广播接收器
        if (playlistUpdateReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(playlistUpdateReceiver);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新数据
        if (adapter != null) {
            adapter.updateData(playlistManager.getAllPlaylists());
        }
    }
}